class Solution
{
public:
    int minOperations(vector<int> &nums1, vector<int> &nums2)
    {
        int n = nums1.size();
        int swap = 0;
        int noSwap = 0;
        int nn1 = nums1[n - 1];
        int nn2 = nums2[n - 1];
        for (int i = 0; i < n - 1; ++i)
        {
            if (nums1[i] <= nn1 && nums1[i] <= nn2 && nums2[i] <= nn1 && nums2[i] <= nn2)
            {
                ++noSwap;
            }
            else if ((nums1[i] > nn1 && nums2[i] > nn1) || (nums1[i] > nn2 && nums2[i] > nn2) || (nums1[i] > nn1 && nums1[i] > nn2) || (nums2[i] > nn1 && nums2[i] > nn2))
            {
                return -1;
            }
            else if (nums1[i] > nn1 || nums2[i] > nn2)
            {
                ++swap;
            }
        }
        return min(swap, n - noSwap - swap);
    }
};